import React, { useState, useEffect, useMemo, useRef } from 'react';
import { Button, Progress } from 'antd';
import xml2Tags from '@/utils/xml2Tags'
import styles from './index.less';

// 学习状态
const LearnStatus = {
  学习前: 0,
  学习中: 1,
  学习完毕: 2
}

export default function (props) {
  const { onNext, dirHandleList } = props
  const [learnStatus, setLearnStatus] = useState(LearnStatus.学习前)
  const [percent, setPercent] = useState(0) // 进度条百分比
  const [tags, setTags] = useState([]) // 约束对象
  const [logs, setlogs] = useState([]) // 学习日志

  // 学习文件夹列表
  const learnDirList = async () => {
    const tags = {
      "!top": [],
      "!attrs": {}
    }
    logInfo('开始学习...')
    let i = 0
    let len = dirHandleList.length
    for (const dirHandle of dirHandleList) {
      setPercent((i * 100 / len).toFixed(2))
      await learnDir(dirHandle, tags)
    }
    setPercent(100)
    setLearnStatus(LearnStatus.学习完毕)
    logInfo('学习完毕，请点击下一步')
    setTags(tags)
  }

  // 记录学习日志
  const logInfo = (text) => {
    logs.push(text);
    setlogs([...logs])
  }

  const logsRef = useRef();

  // 学习日志变化，滚动到底部
  useEffect(() => {
    if (logsRef.current) {
      logsRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [logs]);

  // 学习文件
  const learnDir = async (dirHandle, tags) => {
    for await (const handle of dirHandle.values()) {
      if (handle.kind === 'file') {// 文件
        const file = await handle.getFile()
        if (file.type === 'text/xml') {
          logInfo(`学习文件：${handle.name}`)
          const text = await file.text()
          xml2Tags(text, tags)
        }
      } else { // 文件夹
        await learnDir(handle, tags)
      }
    }
  }

  const handlelearn = () => {
    if (learnStatus === LearnStatus.学习前) {// 点击开始学习
      setLearnStatus(LearnStatus.学习中)
      learnDirList()
    } else if (learnStatus === LearnStatus.学习完毕) { // 点击下一步
      onNext(tags)
    }
  }

  const btnText = useMemo(() => {
    if (learnStatus === LearnStatus.学习前) {
      return '开始学习'
    } else if (learnStatus === LearnStatus.学习中) {
      return '学习中'
    } else if (learnStatus === LearnStatus.学习完毕) {
      return '下一步'
    }
  }, [learnStatus])

  return <div>
    {
      learnStatus !== LearnStatus.学习前 && <div>
        <Progress percent={percent} />
        <ul className={styles.logInfo} >
          {logs.map((log, index) => <li key={index}>{log}</li>)}
          <li ref={logsRef}></li>
        </ul>
      </div>
    }
    <div className={styles['modal-footer']}>
      <Button type="primary" disabled={learnStatus === LearnStatus.学习中} onClick={handlelearn}>{btnText}</Button>
    </div>
  </div>
}
